﻿using System.Net.Sockets;
using MESTranslateToPLC.Schema.Response;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.CodeAnalysis.Diagnostics;

namespace MESTranslateToPLC.Core.Exception;

public class GlobalExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        var exception = context.Exception;
        var statusCode = 500;
        var message = exception.Message;
        var data = new object();
        if (exception is UnauthorizedAccessException)
        {
            statusCode = 401;
            message = "Unauthorized";
        }

        // else if (exception is NotFoundException)
        // {
        //     statusCode = 404;
        //     message = "Not Found";
        // }
        if (exception.InnerException is SocketException)
        {
            statusCode = 404;
            message = $"SocketException:{exception.Message}";
        }
        // 其他自定义异常处理逻辑...

        var result = new JsonResult(new { error = message, data });
        result.StatusCode = statusCode;
        context.Result = result;
    }
}